/*
 * @Author: your name
 * @Date: 1970-01-01 08:00:00
 * @LastEditTime: 2020-08-24 22:48:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /Linux系统编程/pthread_cancle.c
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h> // 线程对应的头文件

void *myfunc(void *arg)
{
  int ret;
  ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  if (ret != 0)
  {
      printf("set cancle state fail\n");
      exit(1);
  }
  printf("i m new thread\n");
  sleep(4);

  printf("about to cancle\n");
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  // 立即取消 设置type为立即取消
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  printf("first cancle point\n");
  return (void *)20;
    
}

int main()
{
    // main 函数里面都是主线程的处理代码
    // 而在回调函数都是子线程
    // 创建一个子线程
    // 线程ID变量
    pthread_t pthid;
    int ret = pthread_create(&pthid, NULL, myfunc, NULL);
    if (ret != 0)
    {
        printf("error number %d\n", ret);
        // 打印错误信息
        printf("%s\n", strerror(ret));
    }
    printf("parent thread id: %lu\n", pthread_self());
    ret = pthread_cancel(pthid);
    // pthread_exit(NULL);
    // sleep(2);

    if (pthread_join(pthid, NULL) == -1)
    {
        printf("error\n");
    }
}
